<template>
  <div class="dialog-container">
    <div class="dialog-content">
      <div class="panel-container">
        <div class="panel-content">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="140px"
          >
            <el-form-item
              label="角色名称:"
              prop="name"
            >
              <el-input
                v-model="form.name"
                type="text"
                style="width: 300px"
                maxlength="20"
              />
            </el-form-item>
            <el-tabs
              v-model="tabActive"
              class="tab-container"
            >
              <el-tab-pane
                label="菜单权限"
                name="1"
              >
                <el-form-item
                  prop="search"
                  label-width="0"
                >
                  <el-input
                    v-model="filterTextMenu"
                    placeholder="请输入内容"
                    class="input-with-select"
                    style="width: 300px"
                    clearable
                  >
                    <el-button
                      slot="append"
                      icon="el-icon-search"
                    />
                  </el-input>
                </el-form-item>
                <div class="scroll">
                  <el-form-item
                    prop="power_code"
                    label-width="0"
                  >
                    <el-tree
                      ref="tree1"
                      :data="menuList"
                      show-checkbox
                      node-key="id"
                      :default-checked-keys="defaultCheckedMenu"
                      :props="defaultPropsMenu"
                      :filter-node-method="filterNode"
                      @check="handleCheckMenu"
                    />
                  </el-form-item>
                </div>
              </el-tab-pane>
              <el-tab-pane
                label="使用人"
                name="2"
              >
                <el-form-item
                  prop="search"
                  label-width="0"
                >
                  <el-input
                    v-model="filterTextUser"
                    placeholder="请输入内容"
                    class="input-with-select"
                    style="width: 300px"
                    clearable
                  >
                    <el-button
                      slot="append"
                      icon="el-icon-search"
                    />
                  </el-input>
                </el-form-item>
                <el-row>
                  <el-col
                    :span="12"
                    class="user-tree"
                  >
                    <div class="scroll">
                      <el-form-item
                        prop="man_ids"
                        label-width="0"
                      >
                        <el-tree
                          ref="tree2"
                          :data="userList"
                          show-checkbox
                          default-expand-all
                          node-key="id"
                          :default-checked-keys="defaultCheckedUser"
                          :props="defaultPropsUser"
                          :filter-node-method="filterNode"
                          @check="handleCheckUser"
                        >
                          <span
                            slot-scope="{ data }"
                            class="custom-tree-node"
                          >
                            <div v-if="data.is_user === 1">
                              <i class="icon el-icon-user-solid" />
                              <span>{{ data.name }}</span>
                            </div>
                            <div v-else>
                              <span>{{ data.name }}</span>
                            </div>
                          </span>
                        </el-tree>
                      </el-form-item>
                    </div>
                  </el-col>
                  <el-col
                    :span="12"
                    class="border"
                  >
                    <div class="scroll">
                      <div class="text-1">
                        已选择{{ showUser.length }}个员工
                      </div>
                      <div class="user-list">
                        <div
                          v-for="item in showUser"
                          :key="item.id"
                          class="item"
                        >
                          <div class="left">
                            <i class="icon el-icon-user-solid" />{{ item.name }}
                          </div>
                          <div class="right">
                            <i
                              class="icon el-icon-close"
                              @click="handleDelete(item.id)"
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </el-tab-pane>
            </el-tabs>
            <el-form-item
              class="fixed-bottom"
              style="margin-bottom: 0; margin-top: 40px"
            >
              <div class="panel-line flex-end">
                <el-button @click="handleCancel">取消</el-button>
                <el-button
                  :loading="loading"
                  type="primary"
                  @click="handleSubmit"
                >
                  保存
                </el-button>
                <el-button
                  v-if="editModel === 'edit'"
                  :loading="loading"
                  type="danger"
                  :disabled="showUser.length > 0 || form.name === 'admin'"
                  @click="handleDeleteRole"
                >
                  删除
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  apiSysRolesAdd,
  apiSysRolesEdit,
  apiSysRolesDel,
  apiSysRolesSelectPermission,
  apiSysRolesSelectUser
} from '@/api/system'

export default {
  name: 'DialogAdd',
  props: {
    roleList: {
      type: Array,
      default: () => {
        return []
      }
    },
    info: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    var validaName = (rule, value, callback) => {
      if (value) {
        const role = this.roleList.find((item) => {
          return item.name === value && item.id !== this.info.id
        })
        if (role) {
          callback(new Error('角色名称不能重复'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      tabActive: '1',
      menuList: [],
      userList: [],
      editModel: 'add',
      defaultPropsMenu: {
        children: 'children',
        label: 'title'
      },
      defaultPropsUser: {
        children: 'children',
        label: 'name'
      },
      form: {
        id: '',
        name: '',
        f_code: [],
        power_code: [],
        man_ids: []
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { validator: validaName, trigger: 'blur' }
        ],
        power_code: [
          { required: true, message: '菜单权限不能为空', trigger: 'blur' }
        ]
      },
      loading: false,
      defaultCheckedMenu: [],
      defaultCheckedUser: [],
      search: '',
      showUser: [],
      filterTextMenu: '',
      filterTextUser: ''
    }
  },
  computed: {},
  watch: {
    filterTextMenu(val) {
      this.$refs.tree1.filter(val)
    },
    filterTextUser(val) {
      this.$refs.tree2.filter(val)
    }
  },
  mounted() {
    if (this.info.id) {
      this.editModel = 'edit'
      this.form.id = this.info.id
      this.form.name = this.info.name
    }
    this.getSelectList()
  },
  methods: {
    getSelectList() {
      apiSysRolesSelectPermission({ id: this.form.id }).then((res) => {
        const index = res.data.find((item) => item.title === '首页')
        if (index) {
          index.disabled = true
          index.checked = true
          index.children &&
            index.children.forEach((item) => {
              item.disabled = true
              item.checked = true
            })
        }
        this.menuList = res.data
        this.defaultCheckedMenu = []
        this.getChecked(this.menuList, 'defaultCheckedMenu', ['id'])
        this.form.power_code = this.defaultCheckedMenu.map((item) => item.id)
      })
      apiSysRolesSelectUser({ id: this.form.id }).then((res) => {
        this.userList = res.data
        this.defaultCheckedUser = []
        this.getChecked(this.userList, 'defaultCheckedUser', ['id'])
        this.getChecked(this.userList, 'showUser', ['id', 'name'])
        this.form.man_ids = this.defaultCheckedUser.map((item) => item.id)
      })
    },
    getChecked(list, checked, props) {
      if (!list) {
        return
      }
      list.forEach((item) => {
        if (item.checked === true) {
          if (props) {
            if (props.length === 1) {
              this[checked].push(item[props[0]])
            } else {
              const obj = {}
              props.forEach((prop) => {
                obj[prop] = item[prop]
              })
              this[checked].push(obj)
            }
          } else {
            this[checked].push(item)
          }
        }
        if (item.children) {
          this.getChecked(item.children, checked, props)
        }
      })
    },
    // 保存
    handleSubmit() {
      this.form.power_code = this.$refs.tree1
        .getCheckedNodes()
        .map((item) => item.id)
      this.form.f_code = this.$refs.tree1
        .getHalfCheckedNodes()
        .map((item) => item.id)
      this.$refs.form.validate((valid, message) => {
        if (!valid) {
          const name = Object.keys(message)[0]
          this.$message.error(message[name][0].message)
          return
        }
        this.form.man_ids = this.showUser.map((item) => item.id)
        if (this.form.man_ids.length === 0) {
          this.$confirm('您未选择使用人，是否继续保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.submit()
          })
        } else {
          this.submit()
        }
      })
    },
    submit() {
      this.loading = true
      if (this.editModel === 'add') {
        apiSysRolesAdd(this.form)
          .then((res) => {
            this.loading = false
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            setTimeout(() => {
              this.$emit('success')
            }, 1000)
          })
          .catch((res) => {
            this.loading = false
          })
      } else {
        apiSysRolesEdit(this.form)
          .then((res) => {
            this.loading = false
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            setTimeout(() => {
              this.$emit('success')
            }, 1000)
          })
          .catch((res) => {
            this.loading = false
          })
      }
    },
    // 取消
    handleCancel() {
      this.$emit('close')
    },
    handleCheckMenu(value, check) {},
    handleCheckUser(value, check) {
      this.showUser = this.$refs.tree2
        .getCheckedNodes()
        .filter((item) => item.is_user === 1)
    },
    filterNode(value, data) {
      if (!value) return true
      if (data.name) {
        return data.name.indexOf(value) !== -1
      }
      if (data.title) {
        return data.title.indexOf(value) !== -1
      }
    },
    handleDelete(id) {
      this.$refs.tree2.setChecked(id, false, true)
      this.showUser = this.$refs.tree2
        .getCheckedNodes()
        .filter((item) => item.is_user === 1)
    },
    handleDeleteRole() {
      window.enterPreventDefault = false
      this.$confirm('确定要删除' + this.form.name + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          window.enterPreventDefault = true
          this.loading = true
          apiSysRolesDel({ ids: [this.form.id] })
            .then(() => {
              this.loading = false
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.$emit('success')
            })
            .catch(() => {
              this.loading = false
            })
        })
        .catch(() => {
          window.enterPreventDefault = true
        })
    }
  }
}
</script>
<style scoped lang="scss">
.tab-container {
  padding-left: 60px;
  padding-bottom: 80px;
}
.border {
  border-left: 1px solid #ddd;
  padding-left: 20px;
}
.user-list {
  margin-top: 15px;
  .item {
    padding: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left {
      .icon {
        margin-right: 2px;
      }
    }
    .right {
      .icon {
        cursor: pointer;
      }
    }
  }
}
.fixed-bottom {
  width: 50%;
  padding: 10px 0;
  padding-right: 40px;
  position: fixed;
  bottom: 0;
  right: 0;
  background: #ffffff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.scroll {
  height: calc(100vh - 300px);
  overflow-y: auto;
}
</style>
<style>
.el-select-dropdown.el-popper {
  min-height: 200px;
}
</style>
